<?php
namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Models\MFeedback;
use App\Models\MNews;
use App\Models\MNotices;
use Illuminate\Http\Request;

/**
 * 内容管理控制器
 */
class ContentController extends Controller
{
    /**
     * 新闻动态和系统公告界面
     * $flag = 0 获取新闻列表
     * $flag = 1 获取系统公告列表
     */
    public function newsPage(Request $request, $flag, $index = 1)
    {
        //开启分页支持
        $this->fyInit(route('sys.news', ['flag' => $flag]), 20, $request->getQueryString());
        $query = null;

        if ($flag == 0) {                    //新闻动态
            $query = (new MNews())->query();
            $query = $query->select(['id', 'title', 'time']);

        } elseif ($flag == 1) {               //系统公告
            $query = (new MNotices())->query();
            $query = $query->select(['id', 'title', 'time', 'start', 'end'])->where('end', '>', time());
        }

        $this->fyCalc($query->count(), $index);
        $this->data['notices'] = $query->skip($this->fy_pgOffset)
            ->take($this->fy_pgSize)->orderBy('time', 'desc')->get(); //[ 按时间 ] 降序 ↓
        $this->data['flag'] = $flag;
        $this->fyViewInit($this->data);
        return view("system.news")->with($this->data);
    }

    /**
     * 内容详情
     * $flag = 0 获取新闻的详情
     * $flag = 1 获取系统公告的详情
     */
    public function contentDetail($flag, $id)
    {
        if ($flag == 0) {
            $news = MNews::find($id);
            return $news->content;
        } elseif ($flag == 1) {
            $notice = MNotices::find($id);
            return $notice->content;
        }
    }

    /**
     * 在线留言界面
     */
    public function feedbackPage(Request $request, $index = 1)
    {
        //开启分页
        $this->fyInit(route("sys.feedback"), 5)->fyCalc(MFeedback::where('uid', ss('uid'))->count(), $index);
        $this->data['feedbacks'] = MFeedback::where('uid', ss('uid'))->skip($this->fy_pgOffset)
            ->take($this->fy_pgSize)
            ->orderBy('time', 'desc')
            ->get();
        $this->fyViewInit($this->data);
        return view("system.feedback")->with($this->data);
    }

    /**
     * 提交留言信息
     */
    public function feedbackSend(Request $request)
    {
        if (!$request->has('message')) {
            $this->data = $this->makeJsCode(1, "请填写留言内容! ");
        }

        if (MFeedback::sendMessage($request->message)) {
            $this->data = $this->makeJsCode(0, "留言成功! ");
        } else {
            $this->data = $this->makeJsCode(1, "留言失败! ");
        }
        return response()->json($this->data);
    }

}